package com.dng.book.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dng.book.dto.BookQueryRequest;
import com.dng.book.entity.Book;
import com.dng.book.mapper.BookMapper;
import com.dng.book.service.BookService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * 书籍服务实现类
 *
 * @author dng
 * @since 2024-01-01
 */
@Slf4j
@Service
public class BookServiceImpl extends ServiceImpl<BookMapper, Book> implements BookService {

    @Override
    public IPage<Book> pageQuery(BookQueryRequest request) {
        Page<Book> page = new Page<>(request.getPageNum(), request.getPageSize());
        
        LambdaQueryWrapper<Book> wrapper = new LambdaQueryWrapper<>();
        
        // 添加查询条件
        if (StrUtil.isNotBlank(request.getBookName())) {
            wrapper.like(Book::getBookName, request.getBookName());
        }
        if (StrUtil.isNotBlank(request.getIsbn())) {
            wrapper.eq(Book::getIsbn, request.getIsbn());
        }
        if (StrUtil.isNotBlank(request.getPublisher())) {
            wrapper.like(Book::getPublisher, request.getPublisher());
        }
        
        // 按创建时间倒序
        wrapper.orderByDesc(Book::getCreatedTime);
        
        return page(page, wrapper);
    }

    @Override
    public boolean addBook(Book book) {
        book.setCreatedTime(LocalDateTime.now());
        book.setUpdatedTime(LocalDateTime.now());
        book.setCreatedBy("admin");
        book.setUpdatedBy("admin");
        return save(book);
    }

    @Override
    public boolean updateBook(Book book) {
        // 使用LambdaUpdateWrapper更新，避免乐观锁问题
        LambdaUpdateWrapper<Book> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Book::getId, book.getId())
                .eq(Book::getDelFlag, "0")
                .set(Book::getBookName, book.getBookName())
                .set(Book::getIsbn, book.getIsbn())
                .set(Book::getPublisher, book.getPublisher())
                .set(Book::getPrice, book.getPrice())
                .set(Book::getPublishDate, book.getPublishDate())
                .set(Book::getUpdatedBy, "admin")
                .set(Book::getUpdatedTime, LocalDateTime.now());
        
        return update(updateWrapper);
    }

    @Override
    public boolean deleteBook(Long id) {
        return removeById(id);
    }
} 